package com.mjk.common.web.getway.restful.filter.gzip;


import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpServletResponseWrapper;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

public class GZipResponseWrapper extends HttpServletResponseWrapper {
		// 默认的 response
		private final HttpServletResponse response;

		// 自定义的 outputStream, 执行close()的时候对数据压缩，并输出
		private GZipOutputStream gzipOutputStream;

		// 自定义 printWriter，将内容输出到 GZipOutputStream 中
		private PrintWriter writer;

		public GZipResponseWrapper(HttpServletResponse response) {
			super(response);
			this.response = response;
		}
		@Override
		public ServletOutputStream getOutputStream() throws IOException {
			if (gzipOutputStream == null)
				gzipOutputStream = new GZipOutputStream(response);
			return gzipOutputStream;
		}
		@Override
		public PrintWriter getWriter() throws IOException {
			if (writer == null)
				writer = new PrintWriter(new OutputStreamWriter(
						new GZipOutputStream(response), StandardCharsets.UTF_8));
			return writer;
		}

		// 压缩后数据长度会发生变化 因此将该方法内容置空
		@Override
		public void setContentLength(int contentLength) {
			//do noting
		}
		@Override
		public void flushBuffer() throws IOException {
			gzipOutputStream.flush();
		}

		public void finishResponse() throws IOException {
			if (gzipOutputStream != null)
				gzipOutputStream.close();
			if (writer != null)
				writer.close();
		}

}
